package com.guo.xiao.bing.controller;

import com.github.pagehelper.PageInfo;
import com.guo.xiao.bing.entity.Note;
import com.guo.xiao.bing.entity.User;
import com.guo.xiao.bing.service.NoteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("note")
public class NoteController {

    @Autowired
    NoteService noteService;

    @RequestMapping(value = "{page}", method = RequestMethod.GET)
    public String list(@PathVariable Integer page, Model model) {
        PageInfo<Note> pageInfo = noteService.find(page);
        model.addAttribute("page", pageInfo);
        return "note/list";
    }

    @RequestMapping(value = "add", method = RequestMethod.GET)
    public String add(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }
        return "note/add";
    }

    @RequestMapping(value = "add", method = RequestMethod.POST)
    public String add(HttpSession session, @ModelAttribute Note note) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }
        note.setUserId(user.getId());
        note.setUsername(user.getUsername());
        noteService.save(note);
        return "redirect:/note/1";
    }


    @RequestMapping(value = "del/{id}", method = RequestMethod.GET)
    public String del(@PathVariable Integer id, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }
        if ("admin".equals(user.getUsername())) {
            noteService.delete(id);
        }

        return "redirect:/note/1";
    }

}
